package com.jsjvm.client.classparser.jconstants;

import com.jsjvm.client.classparser.JConstantPool;
import com.jsjvm.client.execution.JClassLoader.JClassNotLoadedException;
import com.jsjvm.client.execution.objrepr.ArrayRepr;
import com.jsjvm.client.execution.objrepr.ObjectFactory;
import com.jsjvm.client.execution.objrepr.ObjectRepr;
import com.jsjvm.client.util.DataInputStream;

/**
 * The object's value after patching is not initialized. This should be done
 * before <clinit> method is invoked using [charArray].
 */
public class JStringConstant extends JBaseConstant {
	private String value;
	
	public JStringConstant(String value) {
		this.value = value;
	}

	public ArrayRepr getCharArray() throws JClassNotLoadedException {
		ArrayRepr charArray = ObjectFactory.newArray("C", value.length());
		for (int i = 0; i < value.length(); i++) {
			charArray.set(i, (value.charAt(i) & 0xFFFF) );
		}
		return charArray;
	}

	public void setStringObject(ObjectRepr sobj){
		setValue(sobj);
	}
	
	public static JConstant createConstant(int tag, DataInputStream is){
		return new JStringProxyConstant(tag, is);
	}
	
	
	@Override
	public JConstant link(JConstantPool cpool) {
		return this;
	}

	private static class JStringProxyConstant extends JBaseConstant {
		private int valueIdx;

		public JStringProxyConstant(int tag, DataInputStream is) {
			super(tag, is);
			valueIdx = is.readUShort();
		}

		@Override
		public JConstant link(JConstantPool cpool) {
			return new JStringConstant(cpool.getString(valueIdx));
		}

	}
}
